package com.douwong.student.socket;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.douwong.student.activity.ReconnectActivity;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.Config;
import com.douwong.student.factory.ThreadFactory;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.UIUtils;


/**
 * 断线重连处理
 * 
 * @author Administrator
 * 
 */
public class TCPReconnect {

	private static TCPReconnect tcpReconnect;
	public static int reconnectCount = 0;
	private final int count = 3;// 最大的允许重连接次数
	private String TAG = TCPReconnect.class.getSimpleName();

	private TCPReconnect() {}

	public static TCPReconnect getInstance() {
		if (tcpReconnect == null) {
			tcpReconnect = new TCPReconnect();
		}
		return tcpReconnect;
	}

	public synchronized  void reconnectTcp(final Context context){
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (BaseApplication.isCancelConn ||BaseApplication.isCloseConn || !NetUtils.NetwrokIsUseful(UIUtils.getContext())) {
			Log.d(TAG,"老师退出关闭连接或获取在线没有老师在线");
			BaseApplication.isCloseConn=false;
			BaseApplication.isCancelConn=false;
			BaseApplication.isTeaching=false;
			reconnectCount=0;
			Intent intent = new Intent();
			intent.setAction(Config.LOGIN_CLASS_FAILURE);
			context.sendBroadcast(intent);
			BaseApplication.sTeacherOnline=null;
			return;
		}
		Log.w(TAG, "重连次数 ： "+reconnectCount+"   线程："+Thread.currentThread().getName());


		if (reconnectCount < count) {
			reconnectCount++;
			if (!BaseApplication.isLoginClass) {
				ThreadFactory.getNormalPool().execute(new Runnable() {
					@Override
					public void run() {
						LTPServer.createInstance(context).endWork();
						LTPServer.createInstance(context).startWork();
					}
				});

			}
		}else{
			if(reconnectCount==count&&!BaseApplication.isLoginClass&&!ReconnectActivity.isShown){
				reconnectCount=count;
				Log.e(TAG, "连接失败");

				BaseApplication.isCloseConn=false;
				BaseApplication.isCancelConn=false;
				BaseApplication.isTeaching=false;

				Intent intent=new Intent();
				intent.setAction(Config.LOGIN_CLASS_FAILURE);
				context.sendBroadcast(intent);

				Intent failIntent=new Intent();
				failIntent.setClass(context, ReconnectActivity.class);
				failIntent.putExtra("type", "connect");
				failIntent.putExtra("content", "已与教师断开连接，重新加入课堂");
				context.startActivity(failIntent);
				BaseApplication.sTeacherOnline=null;
			}

		}
	}
}
